package service

import (
	"database-platform/dal/db"
	"database-platform/logger"
	"database-platform/model"
	"fmt"
)

// ServerService 服务层结构体

// GetServerList 获取服务器列表
func GetServerList(params *model.ServerListRequest) (*model.ServerListResponse, error) {

	var response = &model.ServerListResponse{}

	var request = &model.Server{
		Hostname: params.Hostname,
		IP:       params.IP,
		Env:      params.Env,
		DBType:   params.DBType,
	}

	result, count, err := db.ListServerRecords(request, params.Page, params.PageSize, params.Search)
	if err != nil {
		return nil, err
	}
	msg := fmt.Sprintf("[service.GetServerList], result: %v, count:%d, request: %v", result, count, request)
	logger.Logger.Warn(msg)

	response.Count = count
	response.Records = result
	response.Page = params.Page
	response.PageSize = params.PageSize

	return response, nil
}

func GetServerById(id int) (*model.Server, error) {
	result, err := db.GetServerRecordById(id)
	if err != nil {
		return nil, err
	}
	msg := fmt.Sprintf("[service.GetServerById], result: %v,  id: %v", result, id)
	logger.Logger.Warn(msg)

	return result, nil
}

// InsertServer 插入服务器记录
func InsertServer(server *model.Server) error {
	err := db.InsertServerRecord(server)
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("[service.InsertServer],  server: %v", server)
	logger.Logger.Warn(msg)

	return nil
}

// UpdateServer 更新服务器记录
func UpdateServer(id int, server *model.Server) error {
	err := db.UpdateServerRecord(id, server)
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("[service.UpdateServer],  server: %v", server)
	logger.Logger.Warn(msg)

	return nil
}

// DeleteServer 删除服务器记录
func DeleteServer(id int) error {
	err := db.DeleteServerRecord(id)
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("[service.DeleteServer],  id: %v", id)
	logger.Logger.Warn(msg)

	return nil
}
